from sqlalchemy import Boolean, Column, DateTime, Enum, Float, ForeignKey, Integer, func
from sqlalchemy.orm import relationship

from app.bot.services.date_time import get_date_time
from app.database.enums import OrderPeriod
from app.database.models.base import Base
from app.database.models.m2ms import allowed_ips_orders, orders_proxies


class Order(Base):
    __tablename__ = "order"

    id = Column(Integer, primary_key=True)
    status = Column(Enum("active", "archive"), server_default="active")
    type = Column(
        Enum("proxy", "subscription", "vpn", "vpn_router"), server_default="proxy"
    )  # TODO Добавить тип vpn_router
    summ = Column(Float, nullable=False)
    summ_total = Column(Float, nullable=False)
    period = Column(Enum(OrderPeriod), nullable=False)
    was_created = Column(DateTime(), server_default=func.now())
    proxies = relationship("Proxy", secondary=orders_proxies, back_populates="orders")
    user = relationship("User", back_populates="orders")
    user_id = Column(Integer, ForeignKey("user.id"))
    allowed_ips = relationship(
        "AllowedIP", secondary=allowed_ips_orders, back_populates="orders"
    )
    category = relationship("Category", back_populates="orders")
    category_id = Column(Integer, ForeignKey("category.id"))
    site = relationship("Site", back_populates="orders")
    site_id = Column(Integer, ForeignKey("site.id"))
    country = relationship("Country", back_populates="orders")
    country_id = Column(Integer, ForeignKey("country.id"))
    provider = relationship("ProxyProvider", back_populates="orders")
    provider_id = Column(Integer, ForeignKey("provider.id"))
    vpn_server = relationship("VPNServer", back_populates="orders")
    vpn_server_id = Column(Integer, ForeignKey("vpn_server.id"))
    auto_renew = Column(Boolean, server_default="0")
    expiring_on = Column(DateTime())  # TODO Заменить на True для впн роутера
    was_renewed = Column(DateTime())
    last_notified = Column(DateTime())

    def __repr__(self):
        if self.type == "subscription":
            return f"<Subscription №{self.id} {self.summ}$ {self.was_created}>"
        elif self.type == "vpn":
            return f"<VPN №{self.id} {self.summ}$ {self.was_created}>"
        elif self.type == "vpn_router":
            return f"<VPN Router №{self.id} {self.summ}$ {self.was_created}>"
        return f"<Order №{self.id} {self.summ}$ {self.was_created}>"

    def __str__(self):
        return self.__repr__()
